package com.entor.select.handler;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import com.mysql.jdbc.ResultSetMetaData;

/**
* @ClassName: BeanListHandler
* @Description: 结果处理器
* @author 林泽
* @date 2018年10月16日 上午10:35:18
*
*/

public class BeanListHandler implements ResultHandler{

	private Class clazzz;
	public BeanListHandler(Class clazzz){
		this.clazzz = clazzz;
	}
	
	public List<Object> handle(ResultSet rs) throws Exception {
		
//		获取构造函数
		Constructor constructor = clazzz.getConstructor();
//		创建对象
		List<Object> datalist = new LinkedList<>();
		while(rs.next()){
			Object object = constructor.newInstance();
//			获取数据库元数据
			java.sql.ResultSetMetaData metaData = rs.getMetaData();
			int count = metaData.getColumnCount();
			for(int i=1;i<=count;i++){
				String column = metaData.getColumnName(i);
				Object columnVlaue = rs.getObject(column);
//				System.out.println((String)columnVlaue);
				Field field = clazzz.getDeclaredField(column);
				field.setAccessible(true);
				field.set(object, columnVlaue);
			}
			datalist.add(object);
		}
		return datalist;
	}
//	public static void main(String[] args) {
//		try {
//			URL url = new URL("https://www.jianshu.com/p/59d36b01608d");
//			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//			InputStream in = conn.getInputStream();
//			InputStreamReader isr = new InputStreamReader(in);
//			BufferedReader br = new BufferedReader(isr);
//			int len = -1;
//			String line = null;
//			while((line = br.readLine())!=null){
//				System.out.println(line);
//			}
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//	}
}
